package com.lds.management.center.common.util;

import com.lds.management.center.common.enums.ErrorEnum;
import com.lds.management.center.common.model.dto.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Slf4j
public class RestUtil {
    private static final RestTemplate REST_TEMPLATE;

    static {
        OkHttp3ClientHttpRequestFactory requestFactory = new OkHttp3ClientHttpRequestFactory();
        requestFactory.setConnectTimeout(20000);
        requestFactory.setReadTimeout(60000);
        requestFactory.setWriteTimeout(20000);
        REST_TEMPLATE = new RestTemplate(requestFactory);
    }


    public static <T> ResultDTO<T> post(String url, Object request, ParameterizedTypeReference<ResultDTO<T>> reference) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<?> httpEntity = new HttpEntity<>(request, headers);
        String wrapperUrl = wrapperUrl(url);

        return post(wrapperUrl, httpEntity, reference);
    }

    private static String wrapperUrl(String url) {
        if (StringUtils.isEmpty(url)) return null;
        if (url.startsWith("http")) return url;
        return "http://" + url;
    }

    private static <T> ResultDTO<T> post(String url, HttpEntity<?> httpEntity, ParameterizedTypeReference<ResultDTO<T>> reference) {
        long startTime = System.nanoTime();
        try {
            ResultDTO<T> result = REST_TEMPLATE.exchange(url, HttpMethod.POST, httpEntity, reference).getBody();
            log.info("POST请求地址:{} 耗时:{} 请求参数:{} 响应结果:{}", url, DateTimeUtil.elapsedTimeMillis(startTime), httpEntity.getBody(), result);
            return result;
        } catch (Exception e) {
            log.error("POST远程调用失败. 请求地址:{} 耗时:{} 请求参数:{} 失败原因={}", url, DateTimeUtil.elapsedTimeMillis(startTime), httpEntity.getBody(), e.getMessage());
            return ResultDTO.fail(ErrorEnum.REST_FAIL);
        }
    }

}
